package com.qf.service.impl;

import com.qf.dao.AddressDao;
import com.qf.dao.OrderDao;
import com.qf.dao.impl.AddressDaoImpl;
import com.qf.dao.impl.OrderDaoImpl;
import com.qf.domain.Address;
import com.qf.service.AddressService;
import com.qf.utils.DataSourceUtils;
import com.qf.utils.TxUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author YDW
 * projectName:shopping
 * time:2022/4/20 20:37
 * description:
 */
public class AddressServiceImpl implements AddressService {
    AddressDao addressDao=new AddressDaoImpl();
    OrderDao orderDao=new OrderDaoImpl();
    @Override
    public List<Address> findAddListByUid(int uid) {
        return addressDao.findAddListByUid(uid);
    }

    @Override
    public void insert(Address address) {
        addressDao.insert(address);
    }

    @Override
    public void deleteAddressByAid(String aid) {
        //查询该地址是否在订单表出现过，如果出现，则不能删除，如果没有则可以删除
        Long count=orderDao.findCountByAid(aid);
        if(count==0){
            addressDao.deleteAddressByAid(aid);
        }else {
            System.out.println("与订单关联，不能删除");
        }

    }

    @Override
    public void update(Address address) {
        addressDao.update(address);
    }

    /*
    * 事务流程
    * try{
    *   开启事务 conn.setAutoCommit(false)   设置不能自动提交
    *   执行具体业务
    *   提交事务： conn.commit();
    * }catch(Exception e){
    *   回滚事务
    * }finally{
    *   结束事务，关闭连接
    * }
    */
    /*
     * 设置用户默认收货地址
     * 1.设置该用户的level=0
     * 2.设置某地址为默认地址
    */







    @Override
    public void defauletAddress(String aid, int uid) {
        Connection conn = TxUtils.getConn();
        try {
            conn.setAutoCommit(false);
            //设置用户所有level都为0
            addressDao.clearDefauletAddress(uid);
            //设置aid=1
            addressDao.setDefauletAddress(aid);
            conn.commit();
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally {
            //移除线程中的连接对象
            TxUtils.remove();
            try {
                conn.close();
                conn.setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}
